//
//  FileMangers.swift
//  JXBaseTools
//
//  Created by godox on 2021/11/30.
//

import Foundation

public enum FMPathType {
    
    case Docment
    case Library(type: LibrarySubPath)
    case Temp
    case AllPath
    
    public enum LibrarySubPath {
        case Caches
        case Preferences
        case Root
    }
    
    var path: String {
        switch self {
        case .Docment: return searchPathWith(pathType: .documentDirectory)
        case .Library(type: .Root): return searchPathWith(pathType: .libraryDirectory)
        case .Library(type: .Caches): return searchPathWith(pathType: .cachesDirectory)
        case .Library(type: .Preferences): return searchPathWith(pathType: .libraryDirectory) + "Preferences"
        case .Temp: return NSTemporaryDirectory()
        case .AllPath: return searchPathWith(pathType: .allApplicationsDirectory)
        }
    }
    
    private func searchPathWith(pathType: FileManager.SearchPathDirectory) -> String {
        return  NSSearchPathForDirectoriesInDomains(pathType, .userDomainMask, true).last!
    }
}



public class FileManagerUtils: NSObject {
    
    
    /// 创建文件夹
    ///
    /// - Parameter path: 路径 在Documents目录下创建
    public class func createDirectory(path: String) {
        if !FileManagerUtils.isDirExists(path: path) {
            do {
                try FileManager.default.createDirectory(atPath: path,
                                                        withIntermediateDirectories: true,
                                                        attributes: nil)
            } catch {
                fatalError("创建文件夹失败")
            }
        }
    }
    
    //文件夹是否存在
    public class func isDirExists(path: String) -> Bool {
        var isDir: ObjCBool = ObjCBool.init(false)
        if FileManager.default.fileExists(atPath: path, isDirectory: &isDir) {
            if isDir.boolValue {
                return isDir.boolValue
            }
            return false
        }
        return false
    }
    
    public class func isFileExists(path: String) -> Bool {
        return FileManager.default.fileExists(atPath: path)
    }
    
    //删除文件
    public class func deleteFile(name: String?, at path: String, isDir: Bool = false) {
        var fullPath: String
        if isDir {
            fullPath = path
        } else {
            fullPath = path + name!
        }
        
        let isDirStr = isDir ? "夹" : ""
        if FileManagerUtils.isFileExists(path: fullPath) {
            do {
                try FileManager.default.removeItem(atPath: fullPath)
                JXLog("删除文件\(isDirStr)成功 \(fullPath)")
            } catch {
                JXLog("删除文件\(isDirStr)失败 \(fullPath)")
            }
        }
    }
    
    //删除文件夹
    public class func deleteDirectory(at path: String) {
        return FileManagerUtils.deleteFile(name: nil, at: path, isDir: true)
    }
    
    //在指定目录下创建文件
    @discardableResult
    public class func createFile(name: String,
                          at path: String,
                          content: Data? = nil,
                          attributes attrs: [FileAttributeKey:Any]? = nil) -> Bool {
        if FileManagerUtils.isDirExists(path: path) {
            
            let filePath = path + name
            return FileManager.default.createFile(atPath: filePath, contents: content, attributes: attrs)
        } else {
            FileManagerUtils.createDirectory(path: path)
        }
        return false
    }
    
    public class func setAttrs(path: String, attributes attrs: [FileAttributeKey: Any]) {
        if FileManagerUtils.isDirExists(path: path) {
            do {
                try FileManager.default.setAttributes(attrs, ofItemAtPath: path)
            } catch {
                JXLog("设置文件属性失败")
            }
        }
        
    }
    
    //删除文件列表
    public class func deleteFiles(at paths: [String]) {
        paths.forEach { path in
            deleteDirectory(at: path)
        }
    }
    
    //读取文件信息
    public class func getItemsAttributes(path: String) -> [FileAttributeKey: Any]? {
        if FileManagerUtils.isFileExists(path: path) {
            do {
                try FileManager.default.attributesOfItem(atPath: path)
            } catch {
                fatalError("读取文件信息失败")
            }
        } else {
            JXLog("文件不存在")
        }
        return nil
    }
    
    public class func getDirs(path: String) -> [String]? {
        if FileManagerUtils.isDirExists(path: path) {
            do {
                return try FileManager.default.contentsOfDirectory(atPath: path)
            } catch {
                fatalError("读取路径的文件列表失败")
            }
        }
        return nil
    }
    
    public class func writeToFile(content: String, path: String, encoding: String.Encoding) {
        if FileManagerUtils.isFileExists(path: path) {
            do {
                try content.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
            } catch {
                fatalError("写入文件失败")
            }
        }
    }
    ///持续写入data文件
    public class func writeDataToFile(_ data: Data?, withPath filePath: String) -> Bool{
       
        if FileManagerUtils.isFileExists(path: filePath){
            do{
                try data?.write(to: URL.init(fileURLWithPath: filePath), options: Data.WritingOptions.atomic)
            }catch{
//                fatalError("失败了")
                return false
                
            }
        }

        return true
    }
    
    
    @discardableResult
    public class func moveFile(from sourcePath: String, to destinationPath: String) -> Bool {
        guard FileManagerUtils.isFileExists(path: sourcePath) else {
            JXLog("源文件不存在")
            return false
        }
        guard !FileManagerUtils.isFileExists(path: destinationPath) else {
            JXLog("目标文件已存在")
            return false
        }
        do {
            try FileManager.default.copyItem(atPath: sourcePath, toPath: destinationPath)
            return true
        } catch {
            fatalError("移动文件失败")
        }
    }
    
}
